package com.lql.sort;

import java.util.*;

/**
 * 堆排序
 */
public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {4, 6, 8, 5, 9};
        int[] ints = new int[8000000];
        Random random = new Random();
        for (int i = 0; i < 8000000; i++) {
            ints[i] = random.nextInt(8000000);
        }
        long startTime = System.currentTimeMillis();
        System.out.println("开始：" + startTime);
        heapSorted(ints);
        long endTime = System.currentTimeMillis();
        System.out.println("结束：" + endTime);
        float l = (endTime - startTime) / 1000f;
        System.out.println("总时间：" + l + "秒");
    }

    /**
     * 实现堆排序
     * @param arr 待排序数组
     */
    public static void heapSorted(int[] arr){
        int temp = 0;
        //将数组调整为大顶堆
        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            heapSort(arr, i, arr.length);
        }
        //交换堆顶元素和最后一个元素
        for (int i = arr.length - 1; i >= 0; i--) {
            temp = arr[i];
            arr[i] = arr[0];
            arr[0] = temp;
            heapSort(arr, 0, i);
        }
//        System.out.println(Arrays.toString(arr));
    }
    /**
     * 将数组调整为大堆顶
     *
     * @param arr    待排序数组
     * @param i      待调整的节点索引
     * @param length 要调整的长度
     */
    public static void heapSort(int[] arr, int i, int length) {
        //记录下当前节点值
        int temp = arr[i];
        for (int j = i * 2 + 1; j < length; j = j * 2 + 1) {
            if (j + 1 < length && arr[j + 1] > arr[j]) {
                //右节点大于左节点的值
                j++;
            }
            if (arr[j] > temp) {
                //右节点值大于当前节点
                arr[i] = arr[j];
                i = j;
            } else {
                break;
            }
            arr[i] = temp;
        }
    }
}
